// pages/goods_list/index.js
import { getGoodsList } from '../../request/goods'
Page({
  data: {
    tabs: [
      {id: 0,value: '综合',isActive: true},
      {id: 1,value: '销量',isActive: false},
      {id: 2,value: '价格',isActive: false}
    ],
    goodsList: []
  },
  //请求参数
  QueryParams: {
    query: '',
    cid: '',
    pagenum: 1,
    pagesize: 10
  },
  totalPage: 1,//总页数

  onLoad: function (options) {
    this.QueryParams.cid = options.cid || ''
    this.QueryParams.query = options.cid || ''
    this.getGoodsList()
  },

  //获取商品列表数据
  async getGoodsList() {
    let data = this.QueryParams
    const goodsList = await getGoodsList(data)
    //获取总条数
    const total = goodsList.total
    //总页数
    this.totalPage = Math.ceil(total / this.QueryParams.pagesize)
    this.setData({
      //拼接数组
      goodsList: [...this.data.goodsList,...goodsList.goods]
    })
    wx.stopPullDownRefresh();
  },

  //标题点击
  handleTabsItemChange(e) {
    const {index} = e.detail
    let {tabs} = this.data
    tabs.forEach((item,number) => {
      number===index?item.isActive=true:item.isActive=false
    });
    this.setData({
      tabs
    })
  },

  //页面上拉触底
  onReachBottom() {
    if (this.QueryParams.pagenum >= this.totalPage) {
      wx.showToast({ title: '没有下一页数据' });
    } else {
      this.QueryParams.pagenum+=1
      this.getGoodsList()
    }
  },

  //页面下拉刷新
  onPullDownRefresh() {
    this.setData({
      goodsList: []
    })
    this.QueryParams.pagenum = 1;
    this.getGoodsList()
  }
})